import axios from 'axios'; // 注意先安装哦
import config from './config.js'; // 导入入默认配置
import store from "@/store"
// import {
//   Message
// } from 'element-ui';
let cancel,
  promiseArr = {};
  axios.defaults.withCredentials=true;
const CancelToken = axios.CancelToken;
//配置全局取消数组
window.__axiosPromiseArr = [];
const instance = axios.create(config);

// instance.interceptors.request.use(
//   function (config) {
//     if (promiseArr[config.url]) {
//       promiseArr[config.url]('操作取消');
//       promiseArr[config.url] = cancel;
//     } else {
//       promiseArr[config.url] = cancel;
//     }
//     // var token = store.state.user.token
//     var token = ""
//     if (token != '' && token != undefined) {
//       config.headers.common['token'] = token

//     }

//     return config;
//   },
//   function (error) {
//     return Promise.resolve(error);
//   }
// );
instance.interceptors.response.use(
  function (response) {
    //console.log(response);
    // 判断是不是登录失效，是的话则触发登录窗口
    if (response.data.code == 40014) {
      // Message('用户登录已过期,请重新登录');
      localStorage.removeItem('api_token');
    }
    return response.data;
  },
  function (error) {
    switch (error.response.status) {
      case 400:
        console.log('请求错误');
        break;
      case 403:
        console.log('未授权，请登录');
        break;
      case 408:
        store.commit('reFresh');
      //请求接口过载的提示
      case 503:
        store.commit('setHotState');
        break;
      case 500:
        store.commit('reFresh');
        break;
      case 501:
        store.commit('reFresh');
        break;
      case 502:
        store.commit('reFresh');
        break;
      default:
    }
    return Promise.reject(error);
  }
);
export default (url = '', data = {}, type = 'GET') => {
  let options = {
    url,
    cancelToken: new CancelToken(c => {
      cancel = c
      window.__axiosPromiseArr.push({
        cancel
      }) //放入一个全局数组，以便之后在router中统一取消
    })
  }
  type = type.toUpperCase();
  return new Promise((resolve, reject) => {
    if (type === 'GET') {
      options = Object.assign(options, {
        method: 'get',
        params: data,
      })
    } else if (type === 'POST') {
      options = Object.assign(options, {
        method: 'POST',
        data: data,
      })
    }
    instance(options)
      .then(res => {
        resolve(res);
        return false
      })
  })
}
